{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 根据廖雪峰教程整理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "from IPython.display import IFrame, display"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 安装git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最早Git是在Linux上开发的，很长一段时间内，Git也只能在Linux和Unix系统上跑。不过，慢慢地有人把它移植到了Windows上。现在，Git可以在Linux、Unix、Mac和Windows这几大平台上正常运行了。\n",
    "\n",
    "要使用Git，第一步当然是安装Git了。根据你当前使用的平台来阅读下面的文字："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在Linux上安装Git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先，你可以试着输入git，看看系统有没有安装Git："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```bash\n",
    "$ git\n",
    "The program 'git' is currently not installed. You can install it by typing:\n",
    "sudo apt-get install git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "像上面的命令，有很多Linux会友好地告诉你Git没有安装，还会告诉你如何安装Git。\n",
    "\n",
    "如果你碰巧用Debian或Ubuntu Linux，通过一条`sudo apt-get install git`就可以直接完成Git的安装，非常简单。\n",
    "\n",
    "老一点的Debian或Ubuntu Linux，要把命令改为`sudo apt-get install git-core`，因为以前有个软件也叫GIT（GNU Interactive Tools），结果Git就只能叫git-core了。由于Git名气实在太大，后来就把GNU Interactive Tools改成gnuit，git-core正式改为git。\n",
    "\n",
    "如果是其他Linux版本，可以直接通过源码安装。先从Git官网下载源码，然后解压，依次输入：`./config，make，sudo make install`这几个命令安装就好了。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在Mac OS X上安装Git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你正在使用Mac做开发，有两种安装Git的方法。\n",
    "\n",
    "一是安装homebrew，然后通过homebrew安装Git，具体方法请参考homebrew的文档：http://brew.sh/。\n",
    "\n",
    "第二种方法更简单，也是推荐的方法，就是直接从AppStore安装Xcode，Xcode集成了Git，不过默认没有安装，你需要运行Xcode，选择菜单“Xcode”->“Preferences”，在弹出窗口中找到“Downloads”，选择“Command Line Tools”，点“Install”就可以完成安装了。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gse2g78bgqj30ou0i8k04.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Xcode是Apple官方IDE，功能非常强大，是开发Mac和iOS App的必选装备，而且是免费的！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在Windows上安装Git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Windows上使用Git，可以从Git官网直接下载安装程序，然后按默认选项安装即可。\n",
    "\n",
    "安装完成后，在开始菜单里找到“Git”->“Git Bash”，蹦出一个类似命令行窗口的东西，就说明Git安装成功！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 设置"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "安装完成后，还需要最后一步设置，在命令行输入：\n",
    "```\n",
    "$ git config --global user.name \"Your Name\"\n",
    "$ git config --global user.email \"email@example.com\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为Git是分布式版本控制系统，所以，每个机器都必须自报家门：你的名字和Email地址。你也许会担心，如果有人故意冒充别人怎么办？这个不必担心，首先我们相信大家都是善良无知的群众，其次，真的有冒充的也是有办法可查的。\n",
    "\n",
    "注意git config命令的--global参数，用了这个参数，表示你这台机器上所有的Git仓库都会使用这个配置，当然也可以对某个仓库指定不同的用户名和Email地址。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 创建版本库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "什么是版本库呢？版本库又名仓库，英文名repository，你可以简单理解成一个目录，这个目录里面的所有文件都可以被Git管理起来，每个文件的修改、删除，Git都能跟踪，以便任何时刻都可以追踪历史，或者在将来某个时刻可以“还原”。\n",
    "\n",
    "所以，创建一个版本库非常简单，首先，选择一个合适的地方，创建一个空目录：\n",
    "```bash\n",
    "$ mkdir learngit\n",
    "$ cd learngit\n",
    "$ pwd\n",
    "/Users/michael/learngit\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`pwd`命令用于显示当前目录。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "第二步，通过git init命令把这个目录变成Git可以管理的仓库：\n",
    "```bash\n",
    "$ git init\n",
    "Initialized empty Git repository in /Users/michael/learngit/.git/\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "瞬间Git就把仓库建好了，而且告诉你是一个空的仓库（empty Git repository），细心的读者可以发现当前目录下多了一个.git的目录，这个目录是Git来跟踪管理版本库的，没事千万不要手动修改这个目录里面的文件，不然改乱了，就把Git仓库给破坏了。\n",
    "\n",
    "如果你没有看到.git目录，那是因为这个目录默认是隐藏的，用`ls -ah`命令就可以看见。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[观看视频](https://www.bilibili.com/video/av51215681?zw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51215681?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7ffe876bc5e0>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#Note that http urls will not be displayed. Only https are allowed inside the Iframe\n",
    "from IPython.display import IFrame\n",
    "IFrame('https://www.bilibili.com/video/av51215681?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也不一定必须在空目录下创建Git仓库，选择一个已经有东西的目录也是可以的。不过，不建议你使用自己正在开发的公司项目来学习Git，否则造成的一切后果概不负责。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 把文件添加到版本库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先这里再明确一下，所有的版本控制系统，其实只能跟踪文本文件的改动，比如TXT文件，网页，所有的程序代码等等，Git也不例外。版本控制系统可以告诉你每次的改动，比如在第5行加了一个单词“Linux”，在第8行删了一个单词“Windows”。而图片、视频这些二进制文件，虽然也能由版本控制系统管理，但没法跟踪文件的变化，只能把二进制文件每次改动串起来，也就是只知道图片从100KB改成了120KB，但到底改了啥，版本控制系统不知道，也没法知道。\n",
    "\n",
    "不幸的是，Microsoft的Word格式是二进制格式，因此，版本控制系统是没法跟踪Word文件的改动的，前面我们举的例子只是为了演示，如果要真正使用版本控制系统，就要以纯文本方式编写文件。\n",
    "\n",
    "因为文本是有编码的，比如中文有常用的GBK编码，日文有Shift_JIS编码，如果没有历史遗留问题，强烈建议使用标准的UTF-8编码，所有语言使用同一种编码，既没有冲突，又被所有平台所支持。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 使用Windows的童鞋要特别注意：\n",
    "\n",
    ">千万不要使用Windows自带的记事本编辑任何文本文件。原因是Microsoft开发记事本的团队使用了一个非常弱智的行为来保存UTF-8编码的文件，他们自作聪明地在每个文件开头添加了0xefbbbf（十六进制）的字符，你会遇到很多不可思议的问题，比如，网页第一行可能会显示一个“?”，明明正确的程序一编译就报语法错误，等等，都是由记事本的弱智行为带来的。建议你下载Visual Studio Code代替记事本，不但功能强大，而且免费！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "言归正传，现在我们编写一个readme.txt文件，内容如下：\n",
    "```bash\n",
    "Git is a version control system.\n",
    "Git is free software.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一定要放到learngit目录下（子目录也行），因为这是一个Git仓库，放到其他地方Git再厉害也找不到这个文件。\n",
    "\n",
    "和把大象放到冰箱需要3步相比，把一个文件放到Git仓库只需要两步。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### git add"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "第一步，用命令`git add`告诉Git，把文件添加到仓库：\n",
    "```bash\n",
    "$ git add readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### git commit"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "执行上面的命令，没有任何显示，这就对了，Unix的哲学是“没有消息就是好消息”，说明添加成功。\n",
    "\n",
    "第二步，用命令`git commit`告诉Git，把文件提交到仓库：\n",
    "```bash\n",
    "$ git commit -m \"wrote a readme file\"\n",
    "[master (root-commit) eaadf4e] wrote a readme file\n",
    " 1 file changed, 2 insertions(+)\n",
    " create mode 100644 readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "简单解释一下`git commit`命令，`-m`后面输入的是本次提交的说明，可以输入任意内容，当然最好是有意义的，这样你就能从历史记录里方便地找到改动记录。\n",
    "\n",
    "嫌麻烦不想输入`-m \"xxx\"`行不行？确实有办法可以这么干，但是强烈不建议你这么干，因为输入说明对自己对别人阅读都很重要。实在不想输入说明的童鞋请自行Google，我不告诉你这个参数。\n",
    "\n",
    "`git commit`命令执行成功后会告诉你，1 file changed：1个文件被改动（我们新添加的readme.txt文件）；2 insertions：插入了两行内容（readme.txt有两行内容）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51215739?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7ffe8e63e730>"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51215739?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为什么Git添加文件需要add，commit一共两步呢？因为commit可以一次提交很多文件，所以你可以多次add不同的文件，比如：\n",
    "```bash\n",
    "$ git add file1.txt\n",
    "$ git add file2.txt file3.txt\n",
    "$ git commit -m \"add 3 files.\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 疑难解答"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Q：输入`git add readme.txt`，得到错误：fatal: not a git repository (or any of the parent directories)。\n",
    "\n",
    "A：Git命令必须在Git仓库目录内执行（git init除外），在仓库目录外执行是没有意义的。\n",
    "\n",
    "Q：输入`git add readme.txt`，得到错误fatal: pathspec 'readme.txt' did not match any files。\n",
    "\n",
    "A：添加某个文件时，该文件必须在当前目录下存在，用ls或者dir命令查看当前目录的文件，看看文件是否存在，或者是否写错了文件名。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在总结一下今天学的两点内容：\n",
    "\n",
    "初始化一个Git仓库，使用git init命令。\n",
    "\n",
    "添加文件到Git仓库，分两步：\n",
    "\n",
    "1. 使用命令`git add` <file>，注意，可反复多次使用，添加多个文件；\n",
    "2. 使用命令`git commit -m` <message>，完成。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 时光穿梭机"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们已经成功地添加并提交了一个readme.txt文件，现在，是时候继续工作了，于是，我们继续修改readme.txt文件，改成如下内容：\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，运行`git status`命令看看结果：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git status`命令可以让我们时刻掌握仓库当前的状态，上面的命令输出告诉我们，readme.txt被修改过了，但还没有准备提交的修改。\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git status`命令可以让我们时刻掌握仓库当前的状态，上面的命令输出告诉我们，readme.txt被修改过了，但还没有准备提交的修改。\n",
    "\n",
    "虽然Git告诉我们readme.txt被修改了，但如果能看看具体修改了什么内容，自然是很好的。比如你休假两周从国外回来，第一天上班时，已经记不清上次怎么修改的readme.txt，所以，需要用`git diff`这个命令看看：\n",
    "```bash\n",
    "$ git diff readme.txt \n",
    "diff --git a/readme.txt b/readme.txt\n",
    "index 46d49bf..9247db6 100644\n",
    "--- a/readme.txt\n",
    "+++ b/readme.txt\n",
    "@@ -1,2 +1,2 @@\n",
    "-Git is a version control system.\n",
    "+Git is a distributed version control system.\n",
    " Git is free software.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git diff`顾名思义就是查看difference，显示的格式正是Unix通用的`diff`格式，可以从上面的命令输出看到，我们在第一行添加了一个distributed单词。\n",
    "\n",
    "知道了对readme.txt作了什么修改后，再把它提交到仓库就放心多了，提交修改和提交新文件是一样的两步，第一步是`git add`：\n",
    "```bash\n",
    "$ git add readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同样没有任何输出。在执行第二步git commit之前，我们再运行git status看看当前仓库的状态：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "  \n",
    "  modified:   readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git告诉我们当前没有需要提交的修改，而且，工作目录是干净（working tree clean）的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51227082?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7ffe8e747d90>"
      ]
     },
     "execution_count": 77,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51227082?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 要随时掌握工作区的状态，使用git status命令。\n",
    "* 如果git status告诉你有文件被修改过，用git diff可以查看修改内容。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 版本回退"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，你已经学会了修改文件，然后把修改提交到Git版本库，现在，再练习一次，修改readme.txt文件如下：\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后尝试提交：\n",
    "```bash\n",
    "$ git add readme.txt\n",
    "$ git commit -m \"append GPL\"\n",
    "[master 1094adb] append GPL\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```\n",
    "\n",
    "像这样，你不断对文件进行修改，然后不断提交修改到版本库里，就好比玩RPG游戏时，每通过一关就会自动把游戏状态存盘，如果某一关没过去，你还可以选择读取前一关的状态。有些时候，在打Boss之前，你会手动存盘，以便万一打Boss失败了，可以从最近的地方重新开始。Git也是一样，每当你觉得文件修改到一定程度的时候，就可以“保存一个快照”，这个快照在Git中被称为commit。一旦你把文件改乱了，或者误删了文件，还可以从最近的一个commit恢复，然后继续工作，而不是把几个月的工作成果全部丢失。\n",
    "\n",
    "现在，我们回顾一下readme.txt文件一共有几个版本被提交到Git仓库里了：\n",
    "\n",
    "版本1：wrote a readme file\n",
    "```bash\n",
    "Git is a version control system.\n",
    "Git is free software.\n",
    "```\n",
    "版本2：add distributed\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software.\n",
    "```\n",
    "版本3：append GPL\n",
    "\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### git log"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当然了，在实际工作中，我们脑子里怎么可能记得一个几千行的文件每次都改了什么内容，不然要版本控制系统干什么。版本控制系统肯定有某个命令可以告诉我们历史记录，在Git中，我们用`git log`命令查看：\n",
    "```bash\n",
    "$ git log\n",
    "commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master)\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 21:06:15 2018 +0800\n",
    "\n",
    "    append GPL\n",
    "\n",
    "commit e475afc93c209a690c39c13a46716e8fa000c366\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 21:03:36 2018 +0800\n",
    "\n",
    "    add distributed\n",
    "\n",
    "commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 20:59:18 2018 +0800\n",
    "\n",
    "    wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git log`命令显示从最近到最远的提交日志，我们可以看到3次提交，最近的一次是append GPL，上一次是add distributed，最早的一次是wrote a readme file。\n",
    "\n",
    "如果嫌输出信息太多，看得眼花缭乱的，可以试试加上`--pretty=oneline`参数：\n",
    "```bash\n",
    "$ git log --pretty=oneline\n",
    "1094adb7b9b3807259d8cb349e7df1d4d6477073 (HEAD -> master) append GPL\n",
    "e475afc93c209a690c39c13a46716e8fa000c366 add distributed\n",
    "eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0 wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "需要友情提示的是，你看到的一大串类似`1094adb...`的是`commit id`（版本号），和SVN不一样，Git的`commit id`不是1，2，3……递增的数字，而是一个SHA1计算出来的一个非常大的数字，用十六进制表示，而且你看到的commit id和我的肯定不一样，以你自己的为准。为什么`commit id`需要用这么一大串数字表示呢？因为Git是分布式的版本控制系统，后面我们还要研究多人在同一个版本库里工作，如果大家都用1，2，3……作为版本号，那肯定就冲突了。\n",
    "\n",
    "每提交一个新版本，实际上Git就会把它们自动串成一条时间线。如果使用可视化工具查看Git历史，就可以更清楚地看到提交历史的时间线："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gse9e0zodcj30os0ayqbe.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### git reset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "好了，现在我们启动时光穿梭机，准备把readme.txt回退到上一个版本，也就是`add distributed`的那个版本，怎么做呢？\n",
    "\n",
    "首先，Git必须知道当前版本是哪个版本，在Git中，用HEAD表示当前版本，也就是最新的提交`1094adb...`（注意我的提交ID和你的肯定不一样），上一个版本就是HEAD^，上上一个版本就是HEAD^^，当然往上100个版本写100个^比较容易数不过来，所以写成HEAD~100。\n",
    "\n",
    "现在，我们要把当前版本`append GPL`回退到上一个版本`add distributed`，就可以使用`git reset`命令：\n",
    "```bash\n",
    "$ git reset --hard HEAD^\n",
    "HEAD is now at e475afc add distributed\n",
    "```\n",
    "--hard参数有啥意义？这个后面再讲，现在你先放心使用。\n",
    "\n",
    "\n",
    "看看readme.txt的内容是不是版本add distributed：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "果然被还原了。\n",
    "\n",
    "还可以继续回退到上一个版本wrote a readme file，不过且慢，让我们用g`it log`再看看现在版本库的状态：\n",
    "```bash\n",
    "$ git log\n",
    "commit e475afc93c209a690c39c13a46716e8fa000c366 (HEAD -> master)\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 21:03:36 2018 +0800\n",
    "\n",
    "    add distributed\n",
    "\n",
    "commit eaadf4e385e865d25c48e7ca9c8395c3f7dfaef0\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 20:59:18 2018 +0800\n",
    "\n",
    "    wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最新的那个版本append GPL已经看不到了！好比你从21世纪坐时光穿梭机来到了19世纪，想再回去已经回不去了，肿么办？\n",
    "\n",
    "办法其实还是有的，只要上面的命令行窗口还没有被关掉，你就可以顺着往上找啊找啊，找到那个append GPL的commit id是1094adb...，于是就可以指定回到未来的某个版本：\n",
    "```bash\n",
    "$ git reset --hard 1094a\n",
    "HEAD is now at 83b0afe append GPL\n",
    "```\n",
    "版本号没必要写全，前几位就可以了，Git会自动去找。当然也不能只写前一两位，因为Git可能会找到多个版本号，就无法确定是哪一个了。\n",
    "\n",
    "再小心翼翼地看看readme.txt的内容：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "果然，我胡汉三又回来了。\n",
    "\n",
    "Git的版本回退速度非常快，因为Git在内部有个指向当前版本的HEAD指针，当你回退版本的时候，Git仅仅是把HEAD从指向append GPL："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gse9mfhjnej31gc07k74p.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "改为指向add distributed："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gse9nfpp50j31k007amxl.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后顺便把工作区的文件更新了。所以你让HEAD指向哪个版本号，你就把当前版本定位在哪。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### git reflog"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，你回退到了某个版本，关掉了电脑，第二天早上就后悔了，想恢复到新版本怎么办？找不到新版本的commit id怎么办？\n",
    "\n",
    "在Git中，总是有后悔药可以吃的。当你用`$ git reset --hard HEAD^`回退到add distributed版本时，再想恢复到append GPL，就必须找到append GPL的`commit id`。Git提供了一个命令`git reflog`用来记录你的每一次命令：\n",
    "```bash\n",
    "$ git reflog\n",
    "e475afc HEAD@{1}: reset: moving to HEAD^\n",
    "1094adb (HEAD -> master) HEAD@{2}: commit: append GPL\n",
    "e475afc HEAD@{3}: commit: add distributed\n",
    "eaadf4e HEAD@{4}: commit (initial): wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "终于舒了口气，从输出可知，`append GPL`的`commit id`是`1094adb`，现在，你又可以乘坐时光机回到未来了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51227163?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7ffe8edebb80>"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51227163?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在总结一下：\n",
    "\n",
    "HEAD指向的版本就是当前版本，因此，Git允许我们在版本的历史之间穿梭，使用命令`git reset --hard commit_id`。\n",
    "\n",
    "穿梭前，用`git log`可以查看提交历史，以便确定要回退到哪个版本。\n",
    "\n",
    "要重返未来，用`git reflog`查看命令历史，以便确定要回到未来的哪个版本。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 工作区和暂存区"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git和其他版本控制系统如SVN的一个不同之处就是有暂存区的概念。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "先来看名词解释。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 工作区（Working Directory）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "就是你在电脑里能看到的目录，比如我的learngit文件夹就是一个工作区："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsea4byl22j31kk0giafm.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 版本库（Repository）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "工作区有一个隐藏目录`.git`，这个不算工作区，而是Git的版本库。\n",
    "\n",
    "Git的版本库里存了很多东西，其中最重要的就是称为`stage`（或者叫`index`）的暂存区，还有Git为我们自动创建的第一个分支`master`，以及指向`master`的一个指针叫`HEAD`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsea5o1dn8j31ks0emaer.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分支和HEAD的概念我们以后再讲。\n",
    "\n",
    "前面讲了我们把文件往Git版本库里添加的时候，是分两步执行的：\n",
    "\n",
    "第一步是用`git add`把文件添加进去，实际上就是把文件修改添加到暂存区；\n",
    "\n",
    "第二步是用`git commit`提交更改，实际上就是把暂存区的所有内容提交到当前分支。\n",
    "\n",
    "因为我们创建`Git`版本库时，`Git`自动为我们创建了唯一一个`master`分支，所以，现在，`git commit`就是往`master`分支上提交更改。\n",
    "\n",
    "你可以简单理解为，需要提交的文件修改通通放到暂存区，然后，一次性提交暂存区的所有修改。\n",
    "\n",
    "俗话说，实践出真知。现在，我们再练习一遍，先对`readme.txt`做个修改，比如加上一行内容：\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，在工作区新增一个LICENSE文本文件（内容随便写）。\n",
    "\n",
    "先用`git status`查看一下状态：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "Untracked files:\n",
    "  (use \"git add <file>...\" to include in what will be committed)\n",
    "\n",
    "\tLICENSE\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git非常清楚地告诉我们，readme.txt被修改了，而LICENSE还从来没有被添加过，所以它的状态是Untracked。\n",
    "\n",
    "现在，使用两次命令`git add`，把readme.txt和LICENSE都添加后，用`git status`再查看一下：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "\n",
    "\tnew file:   LICENSE\n",
    "\tmodified:   readme.txt\n",
    "```\n",
    "现在，暂存区的状态就变成这样了："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gseabrc771j31jk0e2n1f.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所以，`git add`命令实际上就是把要提交的所有修改放到暂存区（`Stage`），然后，执行`git commit`就可以一次性把暂存区的所有修改提交到分支。\n",
    "```bash\n",
    "$ git commit -m \"understand how stage works\"\n",
    "[master e43a48b] understand how stage works\n",
    " 2 files changed, 2 insertions(+)\n",
    " create mode 100644 LICENSE\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一旦提交后，如果你又没有对工作区做任何修改，那么工作区就是“干净”的：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "nothing to commit, working tree clean\n",
    "```\n",
    "现在版本库变成了这样，暂存区就没有任何内容了："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gseai1dz0gj61ke0dy42q02.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51227250?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7ffe8b7be940>"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51227250?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "暂存区是Git非常重要的概念，弄明白了暂存区，就弄明白了Git的很多操作到底干了什么。\n",
    "\n",
    "没弄明白暂存区是怎么回事的童鞋，请向上滚动页面，再看一次。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 管理修改"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，假定你已经完全掌握了暂存区的概念。下面，我们要讨论的就是，为什么Git比其他版本控制系统设计得优秀，因为Git跟踪并管理的是修改，而非文件。\n",
    "\n",
    "你会问，什么是修改？比如你新增了一行，这就是一个修改，删除了一行，也是一个修改，更改了某些字符，也是一个修改，删了一些又加了一些，也是一个修改，甚至创建一个新文件，也算一个修改。\n",
    "\n",
    "为什么说Git管理的是修改，而不是文件呢？我们还是做实验。第一步，对readme.txt做一个修改，比如加一行内容：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，添加：\n",
    "```bash\n",
    "$ git add readme.txt\n",
    "$ git status\n",
    "# On branch master\n",
    "# Changes to be committed:\n",
    "#   (use \"git reset HEAD <file>...\" to unstage)\n",
    "#\n",
    "#       modified:   readme.txt\n",
    "#\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，再修改readme.txt：\n",
    "```bash\n",
    "$ cat readme.txt \n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes of files.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "提交：\n",
    "```bash\n",
    "$ git commit -m \"git tracks changes\"\n",
    "[master 519219b] git tracks changes\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "提交后，再看看状态：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "咦，怎么第二次的修改没有被提交？\n",
    "\n",
    "别激动，我们回顾一下操作过程：\n",
    "\n",
    "第一次修改 -> `git add` -> 第二次修改 -> `git commit`\n",
    "\n",
    "你看，我们前面讲了，Git管理的是修改，当你用`git add`命令后，在工作区的第一次修改被放入暂存区，准备提交，但是，在工作区的第二次修改并没有放入暂存区，所以，`git commit`只负责把暂存区的修改提交了，也就是第一次的修改被提交了，第二次的修改不会被提交。\n",
    "\n",
    "提交后，用`git diff HEAD -- readme.txt`命令可以查看工作区和版本库里面最新版本的区别：\n",
    "```bash\n",
    "$ git diff HEAD -- readme.txt \n",
    "diff --git a/readme.txt b/readme.txt\n",
    "index 76d770f..a9c5755 100644\n",
    "--- a/readme.txt\n",
    "+++ b/readme.txt\n",
    "@@ -1,4 +1,4 @@\n",
    " Git is a distributed version control system.\n",
    " Git is free software distributed under the GPL.\n",
    " Git has a mutable index called stage.\n",
    "-Git tracks changes.\n",
    "+Git tracks changes of files.\n",
    "```\n",
    "可见，第二次修改确实没有被提交。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gseai1dz0gj61ke0dy42q02.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "那怎么提交第二次修改呢？你可以继续`git add`再`git commit`，也可以别着急提交第一次修改，先`git add`第二次修改，再`git commit`，就相当于把两次修改合并后一块提交了：\n",
    "\n",
    "第一次修改 -> `git add` -> 第二次修改 -> `git add` -> `git commit`\n",
    "\n",
    "好，现在，把第二次修改提交了，然后开始小结。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，你又理解了Git是如何跟踪修改的，每次修改，如果不用git add到暂存区，那就不会加入到commit中。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 撤销修改"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自然，你是不会犯错的。不过现在是凌晨两点，你正在赶一份工作报告，你在readme.txt中添加了一行：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes of files.\n",
    "My stupid boss still prefers SVN.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在你准备提交前，一杯咖啡起了作用，你猛然发现了stupid boss可能会让你丢掉这个月的奖金！\n",
    "\n",
    "既然错误发现得很及时，就可以很容易地纠正它。你可以删掉最后一行，手动把文件恢复到上一个版本的状态。如果用git status查看一下：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以发现，Git会告诉你，`git checkout -- file`可以丢弃工作区的修改：\n",
    "```bash\n",
    "$ git checkout -- readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "命令`git checkout -- readme.txt`意思就是，把`readme.txt`文件在工作区的修改全部撤销，这里有两种情况：\n",
    "\n",
    "一种是`readme.txt`自修改后还没有被放到暂存区，现在，撤销修改就回到和版本库一模一样的状态；\n",
    "\n",
    "一种是`readme.txt`已经添加到暂存区后，又作了修改，现在，撤销修改就回到添加到暂存区后的状态。\n",
    "\n",
    "总之，就是让这个文件回到最近一次`git commit`或`git add`时的状态。\n",
    "\n",
    "现在，看看readme.txt的文件内容：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes of files.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "文件内容果然复原了。\n",
    "\n",
    "`git checkout -- file`命令中的`--`很重要，没有`--`，就变成了“切换到另一个分支”的命令，我们在后面的分支管理中会再次遇到`git checkout`命令。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51227817?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7fc774c89640>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51227817?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在假定是凌晨3点，你不但写了一些胡话，还`git add`到暂存区了：\n",
    "```bash\n",
    "$ cat readme.txt\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes of files.\n",
    "My stupid boss still prefers SVN.\n",
    "\n",
    "$ git add readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "庆幸的是，在commit之前，你发现了这个问题。用`git status`查看一下，修改只是添加到了暂存区，还没有提交：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git同样告诉我们，用命令`git reset HEAD <file>`可以把暂存区的修改撤销掉（unstage），重新放回工作区：\n",
    "```bash\n",
    "$ git reset HEAD readme.txt\n",
    "Unstaged changes after reset:\n",
    "M\treadme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git reset`命令既可以回退版本，也可以把暂存区的修改回退到工作区。当我们用HEAD时，表示最新的版本。\n",
    "\n",
    "再用`git status`查看一下，现在暂存区是干净的，工作区有修改：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 最新版的已经改为：  \n",
    ">* 原来的git checkout 可以使用 git restore 代替 \n",
    ">* 原来的git reset HEAD 可以使用 git restore --staged 代替 \n",
    ">* 最新版的git提示都已经更换成了restore"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "又到了小结时间。\n",
    "\n",
    "场景1：当你改乱了工作区某个文件的内容，想直接丢弃工作区的修改时，用命令git restore file。\n",
    "\n",
    "场景2：当你不但改乱了工作区某个文件的内容，还添加到了暂存区时，想丢弃修改，分两步，第一步用命令git restore --unstage <file>，就回到了场景1，第二步按场景1操作。\n",
    "\n",
    "场景3：已经提交了不合适的修改到版本库时，想要撤销本次提交，参考版本回退一节，不过前提是没有推送到远程库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 删除文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Git中，删除也是一个修改操作，我们实战一下，先添加一个新文件test.txt到Git并且提交：\n",
    "```bash\n",
    "$ git add test.txt\n",
    "\n",
    "$ git commit -m \"add test.txt\"\n",
    "[master b84166e] add test.txt\n",
    " 1 file changed, 1 insertion(+)\n",
    " create mode 100644 test.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一般情况下，你通常直接在文件管理器中把没用的文件删了，或者用rm命令删了：\n",
    "```bash\n",
    "$ rm test.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个时候，Git知道你删除了文件，因此，工作区和版本库就不一致了，git status命令会立刻告诉你哪些文件被删除了：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Changes not staged for commit:\n",
    "  (use \"git add/rm <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tdeleted:    test.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在你有两个选择，一是确实要从版本库中删除该文件，那就用命令git rm删掉，并且git commit：\n",
    "```bash\n",
    "$ git rm test.txt\n",
    "rm 'test.txt'\n",
    "\n",
    "$ git commit -m \"remove test.txt\"\n",
    "[master d46f35e] remove test.txt\n",
    " 1 file changed, 1 deletion(-)\n",
    " delete mode 100644 test.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，文件就从版本库中被删除了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51228086?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91aa08dac0>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51228086?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "另一种情况是删错了，因为版本库里还有呢，所以可以很轻松地把误删的文件恢复到最新版本：\n",
    "```bash\n",
    "$ git restore test.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git restore`其实是用版本库里的版本替换工作区的版本，无论工作区是修改还是删除，都可以“一键还原”。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "命令git rm用于删除一个文件。如果一个文件已经被提交到版本库，那么你永远不用担心误删，但是要小心，你只能恢复文件到最新版本，你会丢失最近一次提交后你修改的内容。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 远程仓库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "到目前为止，我们已经掌握了如何在Git仓库里对一个文件进行时光穿梭，你再也不用担心文件备份或者丢失的问题了。\n",
    "\n",
    "可是有用过集中式版本控制系统SVN的童鞋会站出来说，这些功能在SVN里早就有了，没看出Git有什么特别的地方。\n",
    "\n",
    "没错，如果只是在一个仓库里管理文件历史，Git和SVN真没啥区别。为了保证你现在所学的Git物超所值，将来绝对不会后悔，同时为了打击已经不幸学了SVN的童鞋，本章开始介绍Git的杀手级功能之一（注意是之一，也就是后面还有之二，之三……）：远程仓库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你肯定会想，至少需要两台机器才能玩远程库不是？但是我只有一台电脑，怎么玩？\n",
    "\n",
    "其实一台电脑上也是可以克隆多个版本库的，只要不在同一个目录下。不过，现实生活中是不会有人这么傻的在一台电脑上搞几个远程库玩，因为一台电脑上搞几个远程库完全没有意义，而且硬盘挂了会导致所有库都挂掉，所以我也不告诉你在一台电脑上怎么克隆多个仓库。\n",
    "\n",
    "实际情况往往是这样，找一台电脑充当服务器的角色，每天24小时开机，其他每个人都从这个“服务器”仓库克隆一份到自己的电脑上，并且各自把各自的提交推送到服务器仓库里，也从服务器仓库中拉取别人的提交。\n",
    "\n",
    "完全可以自己搭建一台运行Git的服务器，不过现阶段，为了学Git先搭个服务器绝对是小题大作。好在这个世界上有个叫GitHub的神奇的网站，从名字就可以看出，这个网站就是提供Git仓库托管服务的，所以，只要注册一个GitHub账号，就可以免费获得Git远程仓库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在继续阅读后续内容前，请自行注册GitHub账号。由于你的本地Git仓库和GitHub仓库之间的传输是通过SSH加密的，所以，需要一点设置：\n",
    "\n",
    "第1步：创建SSH Key。在用户主目录下，看看有没有.ssh目录，如果有，再看看这个目录下有没有id_rsa和id_rsa.pub这两个文件，如果已经有了，可直接跳到下一步。如果没有，打开Shell（Windows下打开Git Bash），创建SSH Key：\n",
    "```bash\n",
    "$ ssh-keygen -t rsa -C \"youremail@example.com\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你需要把邮件地址换成你自己的邮件地址，然后一路回车，使用默认值即可，由于这个Key也不是用于军事目的，所以也无需设置密码。\n",
    "\n",
    "如果一切顺利的话，可以在用户主目录里找到.ssh目录，里面有id_rsa和id_rsa.pub两个文件，这两个就是SSH Key的秘钥对，id_rsa是私钥，不能泄露出去，id_rsa.pub是公钥，可以放心地告诉任何人。\n",
    "\n",
    "第2步：登陆GitHub，打开“Account settings”，“SSH Keys”页面：\n",
    "\n",
    "然后，点“Add SSH Key”，填上任意Title，在Key文本框里粘贴id_rsa.pub文件的内容："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfhu12gv6j30oo0fwwkn.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "点“Add Key”，你就应该看到已经添加的Key："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfhvop437j31jq0cgjus.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "为什么GitHub需要SSH Key呢？因为GitHub需要识别出你推送的提交确实是你推送的，而不是别人冒充的，而Git支持SSH协议，所以，GitHub只要知道了你的公钥，就可以确认只有你自己才能推送。\n",
    "\n",
    "当然，GitHub允许你添加多个Key。假定你有若干电脑，你一会儿在公司提交，一会儿在家里提交，只要把每台电脑的Key都添加到GitHub，就可以在每台电脑上往GitHub推送了。\n",
    "\n",
    "最后友情提示，在GitHub上免费托管的Git仓库，任何人都可以看到喔（但只有你自己才能改）。所以，不要把敏感信息放进去。\n",
    "\n",
    "如果你不想让别人看到Git库，有两个办法，一个是交点保护费，让GitHub把公开的仓库变成私有的，这样别人就看不见了（不可读更不可写）。另一个办法是自己动手，搭一个Git服务器，因为是你自己的Git服务器，所以别人也是看不见的。这个方法我们后面会讲到的，相当简单，公司内部开发必备。\n",
    "\n",
    "确保你拥有一个GitHub账号后，我们就即将开始远程仓库的学习。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 添加远程库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在的情景是，你已经在本地创建了一个Git仓库后，又想在GitHub创建一个Git仓库，并且让这两个仓库进行远程同步，这样，GitHub上的仓库既可以作为备份，又可以让其他人通过该仓库来协作，真是一举多得。\n",
    "\n",
    "首先，登陆GitHub，然后，在右上角找到“Create a new repo”按钮，创建一个新的仓库："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfhz4apeuj31l00fen1q.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Repository name填入learngit，其他保持默认设置，点击`\"Create repository”`按钮，就成功地创建了一个新的Git仓库："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfi028m0cj31jg0ic7aa.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "目前，在GitHub上的这个learngit仓库还是空的，GitHub告诉我们，可以从这个仓库克隆出新的仓库，也可以把一个已有的本地仓库与之关联，然后，把本地仓库的内容推送到GitHub仓库。\n",
    "\n",
    "现在，我们根据GitHub的提示，在本地的learngit仓库下运行命令：\n",
    "```bash\n",
    "$ git remote add origin git@github.com:michaelliao/learngit.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请千万注意，把上面的michaelliao替换成你自己的GitHub账户名，否则，你在本地关联的就是我的远程库，关联没有问题，但是你以后推送是推不上去的，因为你的SSH Key公钥不在我的账户列表中。\n",
    "\n",
    "添加后，远程库的名字就是origin，这是Git默认的叫法，也可以改成别的，但是origin这个名字一看就知道是远程库。\n",
    "\n",
    "下一步，就可以把本地库的所有内容推送到远程库上：\n",
    "```bash\n",
    "$ git push -u origin master\n",
    "Counting objects: 20, done.\n",
    "Delta compression using up to 4 threads.\n",
    "Compressing objects: 100% (15/15), done.\n",
    "Writing objects: 100% (20/20), 1.64 KiB | 560.00 KiB/s, done.\n",
    "Total 20 (delta 5), reused 0 (delta 0)\n",
    "remote: Resolving deltas: 100% (5/5), done.\n",
    "To github.com:michaelliao/learngit.git\n",
    " * [new branch]      master -> master\n",
    "Branch 'master' set up to track remote branch 'master' from 'origin'.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "把本地库的内容推送到远程，用`git push`命令，实际上是把当前分支master推送到远程。\n",
    "\n",
    "由于远程库是空的，我们第一次推送master分支时，加上了`-u`参数，Git不但会把本地的master分支内容推送的远程新的master分支，还会把本地的master分支和远程的master分支关联起来，在以后的推送或者拉取时就可以简化命令。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51228184?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a6500c70>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51228184?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "推送成功后，可以立刻在GitHub页面中看到远程库的内容已经和本地一模一样："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfi5z63u1j31je0h0jxp.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从现在起，只要本地作了提交，就可以通过命令：\n",
    "```bash\n",
    "$ git push origin master\n",
    "```\n",
    "把本地master分支的最新修改推送至GitHub，现在，你就拥有了真正的分布式版本库！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SSH警告"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当你第一次使用Git的`clone`或者`push`命令连接GitHub时，会得到一个警告：\n",
    "```bash\n",
    "The authenticity of host 'github.com (xx.xx.xx.xx)' can't be established.\n",
    "RSA key fingerprint is xx.xx.xx.xx.xx.\n",
    "Are you sure you want to continue connecting (yes/no)?\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是因为Git使用SSH连接，而SSH连接在第一次验证GitHub服务器的Key时，需要你确认GitHub的Key的指纹信息是否真的来自GitHub的服务器，输入yes回车即可。\n",
    "\n",
    "Git会输出一个警告，告诉你已经把GitHub的Key添加到本机的一个信任列表里了：\n",
    "```bash\n",
    "Warning: Permanently added 'github.com' (RSA) to the list of known hosts.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个警告只会出现一次，后面的操作就不会有任何警告了。\n",
    "\n",
    "如果你实在担心有人冒充GitHub服务器，输入yes前可以对照GitHub的RSA Key的指纹信息是否与SSH连接给出的一致。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 删除远程库"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果添加的时候地址写错了，或者就是想删除远程库，可以用git remote rm <name>命令。使用前，建议先用git remote -v查看远程库信息：\n",
    "```bash\n",
    "$ git remote -v\n",
    "origin  git@github.com:michaelliao/learn-git.git (fetch)\n",
    "origin  git@github.com:michaelliao/learn-git.git (push)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，根据名字删除，比如删除origin：\n",
    "```bash\n",
    "$ git remote rm origin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此处的“删除”其实是解除了本地和远程的绑定关系，并不是物理上删除了远程库。远程库本身并没有任何改动。要真正删除远程库，需要登录到GitHub，在后台页面找到删除按钮再删除。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要关联一个远程库，使用命令`git remote add origin git@server-name:path/repo-name.git`；\n",
    "\n",
    "关联一个远程库时必须给远程库指定一个名字，origin是默认习惯命名；\n",
    "\n",
    "关联后，使用命令`git push -u origin master`第一次推送master分支的所有内容；\n",
    "\n",
    "此后，每次本地提交后，只要有必要，就可以使用命令`git push origin master`推送最新修改；\n",
    "\n",
    "分布式版本系统的最大好处之一是在**本地工作完全不需要考虑远程库的存在**，也就是有没有联网都可以正常工作，而SVN在没有联网的时候是拒绝干活的！当有网络的时候，再把本地提交推送一下就完成了同步，真是太方便了！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 从远程库克隆"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上次我们讲了先有本地库，后有远程库的时候，如何关联远程库。\n",
    "\n",
    "现在，假设我们从零开发，那么最好的方式是先创建远程库，然后，从远程库克隆。\n",
    "\n",
    "首先，登陆GitHub，创建一个新的仓库，名字叫gitskills："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfip33s91j31ks0kggsz.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们勾选`Initialize this repository with a README`，这样GitHub会自动为我们创建一个README.md文件。创建完毕后，可以看到README.md文件："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfipw1gsyj31kk0l4gt1.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，远程库已经准备好了，下一步是用命令git clone克隆一个本地库：\n",
    "```bash\n",
    "$ git clone git@github.com:michaelliao/gitskills.git\n",
    "Cloning into 'gitskills'...\n",
    "remote: Counting objects: 3, done.\n",
    "remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 3\n",
    "Receiving objects: 100% (3/3), done.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意把Git库的地址换成你自己的，然后进入gitskills目录看看，已经有README.md文件了：\n",
    "```bash\n",
    "$ cd gitskills\n",
    "$ ls\n",
    "README.md\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51228298?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7a6a790>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51228298?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果有多个人协作开发，那么每个人各自从远程克隆一份就可以了。\n",
    "\n",
    "你也许还注意到，GitHub给出的地址不止一个，还可以用`https://github.com/michaelliao/gitskills.git`这样的地址。实际上，Git支持多种协议，默认的git://使用ssh，但也可以使用https等其他协议。\n",
    "\n",
    "使用https除了速度慢以外，还有个最大的麻烦是每次推送都必须输入口令，但是在某些只开放http端口的公司内部就无法使用ssh协议而只能用https。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要克隆一个仓库，首先必须知道仓库的地址，然后使用`git clone`命令克隆。\n",
    "\n",
    "Git支持多种协议，包括https，但ssh协议速度最快。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 分支管理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分支就是科幻电影里面的平行宇宙，当你正在电脑前努力学习Git的时候，另一个你正在另一个平行宇宙里努力学习SVN。\n",
    "\n",
    "如果两个平行宇宙互不干扰，那对现在的你也没啥影响。不过，在某个时间点，两个平行宇宙合并了，结果，你既学会了Git又学会了SVN！"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfivc46abj31k20ag77j.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分支在实际中有什么用呢？假设你准备开发一个新功能，但是需要两周才能完成，第一周你写了50%的代码，如果立刻提交，由于代码还没写完，不完整的代码库会导致别人不能干活了。如果等代码全部写完再一次提交，又存在丢失每天进度的巨大风险。\n",
    "\n",
    "现在有了分支，就不用怕了。你创建了一个属于你自己的分支，别人看不到，还继续在原来的分支上正常工作，而你在自己的分支上干活，想提交就提交，直到开发完毕后，再一次性合并到原来的分支上，这样，既安全，又不影响别人工作。\n",
    "\n",
    "其他版本控制系统如SVN等都有分支管理，但是用过之后你会发现，这些版本控制系统创建和切换分支比蜗牛还慢，简直让人无法忍受，结果分支功能成了摆设，大家都不去用。\n",
    "\n",
    "但Git的分支是与众不同的，无论创建、切换和删除分支，Git在1秒钟之内就能完成！无论你的版本库是1个文件还是1万个文件。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建与合并分支"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在版本回退里，你已经知道，每次提交，Git都把它们串成一条时间线，这条时间线就是一个分支。截止到目前，只有一条时间线，在Git里，这个分支叫主分支，即master分支。HEAD严格来说不是指向提交，而是指向master，master才是指向提交的，所以，HEAD指向的就是当前分支。\n",
    "\n",
    "一开始的时候，master分支是一条线，Git用master指向最新的提交，再用HEAD指向master，就能确定当前分支，以及当前分支的提交点："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfiz5qugtj31lg09qjs9.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "每次提交，master分支都会向前移动一步，这样，随着你不断提交，master分支的线也越来越长。\n",
    "\n",
    "当我们创建新的分支，例如dev时，Git新建了一个指针叫dev，指向master相同的提交，再把HEAD指向dev，就表示当前分支在dev上："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfj05h1gdj31g00d075e.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你看，Git创建一个分支很快，因为除了增加一个dev指针，改改HEAD的指向，工作区的文件都没有任何变化！\n",
    "\n",
    "不过，从现在开始，对工作区的修改和提交就是针对dev分支了，比如新提交一次后，dev指针往前移动一步，而master指针不变："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfj11dvzuj31k20didh1.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "假如我们在dev上的工作完成了，就可以把dev合并到master上。Git怎么合并呢？最简单的方法，就是直接把master指向dev的当前提交，就完成了合并："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfj20omnhj31ja0d275h.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "所以Git合并分支也很快！就改改指针，工作区内容也不变！\n",
    "\n",
    "合并完分支后，甚至可以删除dev分支。删除dev分支就是把dev指针给删掉，删掉后，我们就剩下了一条master分支："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfj2l2nthj31is0a20tl.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "真是太神奇了，你看得出来有些提交是通过分支完成的吗？\n",
    "\n",
    "下面开始实战。\n",
    "\n",
    "首先，我们创建dev分支，然后切换到dev分支：\n",
    "```bash\n",
    "$ git checkout -b dev\n",
    "Switched to a new branch 'dev'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "git checkout命令加上-b参数表示创建并切换，相当于以下两条命令：\n",
    "```bash\n",
    "$ git branch dev\n",
    "$ git checkout dev\n",
    "Switched to branch 'dev'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，用git branch命令查看当前分支：\n",
    "```bash\n",
    "$ git branch\n",
    "* dev\n",
    "  master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "git branch命令会列出所有分支，当前分支前面会标一个*号。\n",
    "\n",
    "然后，我们就可以在dev分支上正常提交，比如对readme.txt做个修改，加上一行：\n",
    "```bash\n",
    "Creating a new branch is quick.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后提交：\n",
    "```bash\n",
    "$ git add readme.txt \n",
    "$ git commit -m \"branch test\"\n",
    "[dev b17d20e] branch test\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，dev分支的工作完成，我们就可以切换回master分支：\n",
    "```bash\n",
    "$ git checkout master\n",
    "Switched to branch 'master'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "切换回master分支后，再查看一个readme.txt文件，刚才添加的内容不见了！因为那个提交是在dev分支上，而master分支此刻的提交点并没有变："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsfjagc6bqj31k60digmt.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，我们把dev分支的工作成果合并到master分支上：\n",
    "```bash\n",
    "$ git merge dev\n",
    "Updating d46f35e..b17d20e\n",
    "Fast-forward\n",
    " readme.txt | 1 +\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`git merge`命令用于合并指定分支到当前分支。合并后，再查看readme.txt的内容，就可以看到，和dev分支的最新提交是完全一样的。\n",
    "\n",
    "注意到上面的`Fast-forward`信息，Git告诉我们，这次合并是“快进模式”，也就是直接把master指向dev的当前提交，所以合并速度非常快。\n",
    "\n",
    "当然，也不是每次合并都能`Fast-forward`，我们后面会讲其他方式的合并。\n",
    "\n",
    "合并完成后，就可以放心地删除dev分支了：\n",
    "```bash\n",
    "$ git branch -d dev\n",
    "Deleted branch dev (was b17d20e).\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除后，查看branch，就只剩下master分支了：\n",
    "```bash\n",
    "$ git branch\n",
    "* master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为创建、合并和删除分支非常快，所以Git鼓励你使用分支完成某个任务，合并后再删掉分支，这和直接在master分支上工作效果是一样的，但过程更安全。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51228618?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7d66040>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51228618?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### switch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们注意到切换分支使用git checkout <branch>，而前面讲过的撤销修改则是git checkout -- <file>，同一个命令，有两种作用，确实有点令人迷惑。\n",
    "\n",
    "实际上，切换分支这个动作，用switch更科学。因此，最新版本的Git提供了新的`git switch`命令来切换分支：\n",
    "\n",
    "创建并切换到新的dev分支，可以使用：\n",
    "```bash\n",
    "$ git switch -c dev\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "直接切换到已有的master分支，可以使用：\n",
    "```bash\n",
    "$ git switch master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用新的git switch命令，比git checkout要更容易理解。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "Git鼓励大量使用分支：\n",
    "\n",
    "查看分支：`git branch`\n",
    "\n",
    "创建分支：`git branch <name>`\n",
    "\n",
    "切换分支：`git checkout <name>`或者`git switch <name>`\n",
    "\n",
    "创建+切换分支：`git checkout -b <name>`或者`git switch -c <name>`\n",
    "\n",
    "合并某分支到当前分支：`git merge <name>`\n",
    "\n",
    "删除分支：`git branch -d <name>`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 解决冲突"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "人生不如意之事十之八九，合并分支往往也不是一帆风顺的。\n",
    "\n",
    "准备新的feature1分支，继续我们的新分支开发：\n",
    "```bash\n",
    "$ git switch -c feature1\n",
    "Switched to a new branch 'feature1'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "修改readme.txt最后一行，改为：\n",
    "```bash\n",
    "Creating a new branch is quick AND simple.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在feature1分支上提交：\n",
    "```bash\n",
    "$ git add readme.txt\n",
    "\n",
    "$ git commit -m \"AND simple\"\n",
    "[feature1 14096d0] AND simple\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "切换到master分支：\n",
    "```bash\n",
    "$ git switch master\n",
    "Switched to branch 'master'\n",
    "Your branch is ahead of 'origin/master' by 1 commit.\n",
    "  (use \"git push\" to publish your local commits)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git还会自动提示我们当前master分支比远程的master分支要超前1个提交。\n",
    "\n",
    "在master分支上把readme.txt文件的最后一行改为：\n",
    "```bash\n",
    "Creating a new branch is quick & simple.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "提交：\n",
    "```bash\n",
    "$ git add readme.txt \n",
    "$ git commit -m \"& simple\"\n",
    "[master 5dc6824] & simple\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，master分支和feature1分支各自都分别有新的提交，变成了这样："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这种情况下，Git无法执行“快速合并”，只能试图把各自的修改合并起来，但这种合并就可能会有冲突，我们试试看：\n",
    "```bash\n",
    "$ git merge feature1\n",
    "Auto-merging readme.txt\n",
    "CONFLICT (content): Merge conflict in readme.txt\n",
    "Automatic merge failed; fix conflicts and then commit the result.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "果然冲突了！Git告诉我们，readme.txt文件存在冲突，必须手动解决冲突后再提交。git status也可以告诉我们冲突的文件：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Your branch is ahead of 'origin/master' by 2 commits.\n",
    "  (use \"git push\" to publish your local commits)\n",
    "\n",
    "You have unmerged paths.\n",
    "  (fix conflicts and run \"git commit\")\n",
    "  (use \"git merge --abort\" to abort the merge)\n",
    "\n",
    "Unmerged paths:\n",
    "  (use \"git add <file>...\" to mark resolution)\n",
    "\n",
    "\tboth modified:   readme.txt\n",
    "\n",
    "no changes added to commit (use \"git add\" and/or \"git commit -a\")\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以直接查看readme.txt的内容：\n",
    "```bash\n",
    "Git is a distributed version control system.\n",
    "Git is free software distributed under the GPL.\n",
    "Git has a mutable index called stage.\n",
    "Git tracks changes of files.\n",
    "<<<<<<< HEAD\n",
    "Creating a new branch is quick & simple.\n",
    "=======\n",
    "Creating a new branch is quick AND simple.\n",
    ">>>>>>> feature1\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git用<<<<<<<，=======，>>>>>>>标记出不同分支的内容，我们修改如下后保存：\n",
    "```bash\n",
    "Creating a new branch is quick and simple.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再提交：\n",
    "```bash\n",
    "$ git add readme.txt \n",
    "$ git commit -m \"conflict fixed\"\n",
    "[master cf810e4] conflict fixed\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，master分支和feature1分支变成了下图所示："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsgbj0xku3j30z20gcjt1.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用带参数的`git log`也可以看到分支的合并情况：\n",
    "```bash\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "*   cf810e4 (HEAD -> master) conflict fixed\n",
    "|\\  \n",
    "| * 14096d0 (feature1) AND simple\n",
    "* | 5dc6824 & simple\n",
    "|/  \n",
    "* b17d20e branch test\n",
    "* d46f35e (origin/master) remove test.txt\n",
    "* b84166e add test.txt\n",
    "* 519219b git tracks changes\n",
    "* e43a48b understand how stage works\n",
    "* 1094adb append GPL\n",
    "* e475afc add distributed\n",
    "* eaadf4e wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，删除feature1分支：\n",
    "```bash\n",
    "$ git branch -d feature1\n",
    "Deleted branch feature1 (was 14096d0).\n",
    "```\n",
    "工作完成。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51228780?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7bf3c40>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51228780?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当Git无法自动合并分支时，就必须首先解决冲突。解决冲突后，再提交，合并完成。\n",
    "\n",
    "解决冲突就是把Git合并失败的文件手动编辑为我们希望的内容，再提交。\n",
    "\n",
    "用`git log --graph`命令可以看到分支合并图。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 分支管理策略"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "通常，合并分支时，如果可能，Git会用Fast forward模式，但这种模式下，删除分支后，会丢掉分支信息。\n",
    "\n",
    "如果要强制禁用Fast forward模式，Git就会在merge时生成一个新的commit，这样，从分支历史上就可以看出分支信息。\n",
    "\n",
    "下面我们实战一下--no-ff方式的git merge：\n",
    "\n",
    "首先，仍然创建并切换dev分支：\n",
    "```bash\n",
    "$ git switch -c dev\n",
    "Switched to a new branch 'dev'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "修改readme.txt文件，并提交一个新的commit：\n",
    "```bash\n",
    "$ git add readme.txt \n",
    "$ git commit -m \"add merge\"\n",
    "[dev f52c633] add merge\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，我们切换回master：\n",
    "```bash\n",
    "$ git switch master\n",
    "Switched to branch 'master'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "准备合并dev分支，请注意--no-ff参数，表示禁用Fast forward：\n",
    "```bash\n",
    "$ git merge --no-ff -m \"merge with no-ff\" dev\n",
    "Merge made by the 'recursive' strategy.\n",
    " readme.txt | 1 +\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为本次合并要创建一个新的commit，所以加上-m参数，把commit描述写进去。\n",
    "\n",
    "合并后，我们用git log看看分支历史：\n",
    "```bash\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "*   e1e9c68 (HEAD -> master) merge with no-ff\n",
    "|\\  \n",
    "| * f52c633 (dev) add merge\n",
    "|/  \n",
    "*   cf810e4 conflict fixed\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，不使用Fast forward模式，merge后就像这样："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsgbt12bihj31kc0fiabn.jpg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229040?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7a62ac0>"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51229040?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 分支策略"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在实际开发中，我们应该按照几个基本原则进行分支管理：\n",
    "\n",
    "首先，master分支应该是非常稳定的，也就是仅用来发布新版本，平时不能在上面干活；\n",
    "\n",
    "那在哪干活呢？干活都在dev分支上，也就是说，dev分支是不稳定的，到某个时候，比如1.0版本发布时，再把dev分支合并到master上，在master分支发布1.0版本；\n",
    "\n",
    "你和你的小伙伴们每个人都在dev分支上干活，每个人都有自己的分支，时不时地往dev分支上合并就可以了。\n",
    "\n",
    "所以，团队合作的分支看起来就像这样："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsgbv0d36dj31kk080wgb.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git分支十分强大，在团队开发中应该充分应用。\n",
    "\n",
    "合并分支时，加上`--no-ff`参数就可以用普通模式合并，合并后的历史有分支，能看出来曾经做过合并，而`fast forward`合并就看不出来曾经做过合并。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bug分支"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "软件开发中，bug就像家常便饭一样。有了bug就需要修复，在Git中，由于分支是如此的强大，所以，每个bug都可以通过一个新的临时分支来修复，修复后，合并分支，然后将临时分支删除。\n",
    "\n",
    "当你接到一个修复一个代号101的bug的任务时，很自然地，你想创建一个分支issue-101来修复它，但是，等等，当前正在dev上进行的工作还没有提交：\n",
    "```bash\n",
    "$ git status\n",
    "On branch dev\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "\n",
    "\tnew file:   hello.py\n",
    "\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "并不是你不想提交，而是工作只进行到一半，还没法提交，预计完成还需1天时间。但是，必须在两个小时内修复该bug，怎么办？\n",
    "\n",
    "幸好，Git还提供了一个stash功能，可以把当前工作现场“储藏”起来，等以后恢复现场后继续工作：\n",
    "```bash\n",
    "$ git stash\n",
    "Saved working directory and index state WIP on dev: f52c633 add merge\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，用`git status`查看工作区，就是干净的（除非有没有被Git管理的文件），因此可以放心地创建分支来修复bug。\n",
    "\n",
    "首先确定要在哪个分支上修复bug，假定需要在master分支上修复，就从master创建临时分支：\n",
    "```bash\n",
    "$ git switch master\n",
    "Switched to branch 'master'\n",
    "Your branch is ahead of 'origin/master' by 6 commits.\n",
    "  (use \"git push\" to publish your local commits)\n",
    "\n",
    "$ git switch -c issue-101\n",
    "Switched to a new branch 'issue-101'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在修复bug，需要把“Git is free software ...”改为“Git is a free software ...”，然后提交：\n",
    "```bash\n",
    "$ git add readme.txt \n",
    "$ git commit -m \"fix bug 101\"\n",
    "[issue-101 4c805e2] fix bug 101\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "修复完成后，切换到master分支，并完成合并，最后删除issue-101分支：\n",
    "```bash\n",
    "$ git switch master\n",
    "Switched to branch 'master'\n",
    "Your branch is ahead of 'origin/master' by 6 commits.\n",
    "  (use \"git push\" to publish your local commits)\n",
    "\n",
    "$ git merge --no-ff -m \"merged bug fix 101\" issue-101\n",
    "Merge made by the 'recursive' strategy.\n",
    " readme.txt | 2 +-\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "太棒了，原计划两个小时的bug修复只花了5分钟！现在，是时候接着回到dev分支干活了！\n",
    "```bash\n",
    "$ git switch dev\n",
    "Switched to branch 'dev'\n",
    "\n",
    "$ git status\n",
    "On branch dev\n",
    "nothing to commit, working tree clean\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "工作区是干净的，刚才的工作现场存到哪去了？用git stash list命令看看：\n",
    "```bash\n",
    "$ git stash list\n",
    "stash@{0}: WIP on dev: f52c633 add merge\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "工作现场还在，Git把stash内容存在某个地方了，但是需要恢复一下，有两个办法：\n",
    "\n",
    "一是用`git stash apply`恢复，但是恢复后，`stash`内容并不删除，你需要用`git stash drop`来删除；\n",
    "\n",
    "另一种方式是用`git stash pop`，恢复的同时把`stash`内容也删了：\n",
    "```bash\n",
    "$ git stash pop\n",
    "On branch dev\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "\n",
    "\tnew file:   hello.py\n",
    "\n",
    "Changes not staged for commit:\n",
    "  (use \"git add <file>...\" to update what will be committed)\n",
    "  (use \"git checkout -- <file>...\" to discard changes in working directory)\n",
    "\n",
    "\tmodified:   readme.txt\n",
    "\n",
    "Dropped refs/stash@{0} (5d677e2ee266f39ea296182fb2354265b91b3b2a)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用`git stash list`查看，就看不到任何stash内容了：\n",
    "```bash\n",
    "$ git stash list\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以多次stash，恢复的时候，先用git stash list查看，然后恢复指定的stash，用命令：\n",
    "```bash\n",
    "$ git stash apply stash@{0}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229109?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7dc53a0>"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51229109?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在master分支上修复了bug后，我们要想一想，dev分支是早期从master分支分出来的，所以，这个bug其实在当前dev分支上也存在。\n",
    "\n",
    "那怎么在dev分支上修复同样的bug？重复操作一次，提交不就行了？\n",
    "\n",
    "有木有更简单的方法？\n",
    "\n",
    "有！\n",
    "\n",
    "同样的bug，要在dev上修复，我们只需要把4c805e2 fix bug 101这个提交所做的修改“复制”到dev分支。注意：我们只想复制4c805e2 fix bug 101这个提交所做的修改，并不是把整个master分支merge过来。\n",
    "\n",
    "为了方便操作，Git专门提供了一个`cherry-pick`命令，让我们能复制一个特定的提交到当前分支：\n",
    "```bash\n",
    "$ git branch\n",
    "* dev\n",
    "  master\n",
    "$ git cherry-pick 4c805e2\n",
    "[master 1d4b803] fix bug 101\n",
    " 1 file changed, 1 insertion(+), 1 deletion(-)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Git自动给dev分支做了一次提交，注意这次提交的commit是1d4b803，它并不同于master的4c805e2，因为这两个commit只是改动相同，但确实是两个不同的commit。用`git cherry-pick`，我们就不需要在dev分支上手动再把修bug的过程重复一遍。\n",
    "\n",
    "有些聪明的童鞋会想了，既然可以在master分支上修复bug后，在dev分支上可以“重放”这个修复过程，那么直接在dev分支上修复bug，然后在master分支上“重放”行不行？当然可以，不过你仍然需要`git stash`命令保存现场，才能从dev分支切换到master分支。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "修复bug时，我们会通过创建新的bug分支进行修复，然后合并，最后删除；\n",
    "\n",
    "当手头工作没有完成时，先把工作现场`git stash`一下，然后去修复bug，修复后，再`git stash pop`，回到工作现场；\n",
    "\n",
    "在master分支上修复的bug，想要合并到当前dev分支，可以用`git cherry-pick <commit>`命令，把bug提交的修改“复制”到当前分支，避免重复劳动。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Feature分支"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "软件开发中，总有无穷无尽的新的功能要不断添加进来。\n",
    "\n",
    "添加一个新功能时，你肯定不希望因为一些实验性质的代码，把主分支搞乱了，所以，每添加一个新功能，最好新建一个feature分支，在上面开发，完成后，合并，最后，删除该feature分支。\n",
    "\n",
    "现在，你终于接到了一个新任务：开发代号为Vulcan的新功能，该功能计划用于下一代星际飞船。\n",
    "\n",
    "于是准备开发：\n",
    "```bash\n",
    "$ git switch -c feature-vulcan\n",
    "Switched to a new branch 'feature-vulcan'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "5分钟后，开发完毕：\n",
    "```bash\n",
    "$ git add vulcan.py\n",
    "\n",
    "$ git status\n",
    "On branch feature-vulcan\n",
    "Changes to be committed:\n",
    "  (use \"git reset HEAD <file>...\" to unstage)\n",
    "\n",
    "\tnew file:   vulcan.py\n",
    "\n",
    "$ git commit -m \"add feature vulcan\"\n",
    "[feature-vulcan 287773e] add feature vulcan\n",
    " 1 file changed, 2 insertions(+)\n",
    " create mode 100644 vulcan.py\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "切回dev，准备合并：\n",
    "```bash\n",
    "$ git switch dev\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一切顺利的话，feature分支和bug分支是类似的，合并，然后删除。\n",
    "\n",
    "但是！\n",
    "\n",
    "就在此时，接到上级命令，因经费不足，新功能必须取消！\n",
    "\n",
    "虽然白干了，但是这个包含机密资料的分支还是必须就地销毁：\n",
    "```bash\n",
    "$ git branch -d feature-vulcan\n",
    "error: The branch 'feature-vulcan' is not fully merged.\n",
    "If you are sure you want to delete it, run 'git branch -D feature-vulcan'.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "销毁失败。Git友情提醒，feature-vulcan分支还没有被合并，如果删除，将丢失掉修改，如果要强行删除，需要使用大写的-D参数。。\n",
    "\n",
    "现在我们强行删除：\n",
    "```bash\n",
    "$ git branch -D feature-vulcan\n",
    "Deleted branch feature-vulcan (was 287773e).\n",
    "```\n",
    "终于删除成功！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229185?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7c16a00>"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51229185?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "开发一个新feature，最好新建一个分支；\n",
    "\n",
    "如果要丢弃一个没有被合并过的分支，可以通过git branch -D <name>强行删除。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多人协作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当你从远程仓库克隆时，实际上Git自动把本地的master分支和远程的master分支对应起来了，并且，远程仓库的默认名称是origin。\n",
    "\n",
    "要查看远程库的信息，用`git remote`：\n",
    "```bash\n",
    "$ git remote\n",
    "origin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "或者，用git remote -v显示更详细的信息：\n",
    "```bash\n",
    "$ git remote -v\n",
    "origin  git@github.com:michaelliao/learngit.git (fetch)\n",
    "origin  git@github.com:michaelliao/learngit.git (push)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面显示了可以抓取和推送的origin的地址。如果没有推送权限，就看不到push的地址。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 推送分支\n",
    "\n",
    "推送分支，就是把该分支上的所有本地提交推送到远程库。推送时，要指定本地分支，这样，Git就会把该分支推送到远程库对应的远程分支上\n",
    "```bash\n",
    "$ git push origin master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果要推送其他分支，比如dev，就改成：\n",
    "```bash\n",
    "$ git push origin dev\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但是，并不是一定要把本地分支往远程推送，那么，哪些分支需要推送，哪些不需要呢？\n",
    "* master分支是主分支，因此要时刻与远程同步；\n",
    "* dev分支是开发分支，团队所有成员都需要在上面工作，所以也需要与远程同步；\n",
    "* bug分支只用于在本地修复bug，就没必要推到远程了，除非老板要看看你每周到底修复了几个bug；\n",
    "* feature分支是否推到远程，取决于你是否和你的小伙伴合作在上面开发。\n",
    "\n",
    "总之，就是在Git中，分支完全可以在本地自己藏着玩，是否推送，视你的心情而定！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229249?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91aa0baca0>"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51229249?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 抓取分支\n",
    "\n",
    "多人协作时，大家都会往master和dev分支上推送各自的修改。\n",
    "\n",
    "现在，模拟一个你的小伙伴，可以在另一台电脑（注意要把SSH Key添加到GitHub）或者同一台电脑的另一个目录下克隆：\n",
    "```bash\n",
    "$ git clone git@github.com:michaelliao/learngit.git\n",
    "Cloning into 'learngit'...\n",
    "remote: Counting objects: 40, done.\n",
    "remote: Compressing objects: 100% (21/21), done.\n",
    "remote: Total 40 (delta 14), reused 40 (delta 14), pack-reused 0\n",
    "Receiving objects: 100% (40/40), done.\n",
    "Resolving deltas: 100% (14/14), done.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当你的小伙伴从远程库clone时，默认情况下，你的小伙伴只能看到本地的master分支。不信可以用git branch命令看看：\n",
    "```bash\n",
    "$ git branch\n",
    "* master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，你的小伙伴要在dev分支上开发，就必须创建远程origin的dev分支到本地，于是他用这个命令创建本地dev分支：\n",
    "```bash\n",
    "$ git checkout -b dev origin/dev\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，他就可以在dev上继续修改，然后，时不时地把dev分支push到远程：\n",
    "```bash\n",
    "$ git add env.tx\n",
    "\n",
    "$ git commit -m \"add env\"\n",
    "[dev 7a5e5dd] add env\n",
    " 1 file changed, 1 insertion(+)\n",
    " create mode 100644 env.txt\n",
    "\n",
    "$ git push origin dev\n",
    "Counting objects: 3, done.\n",
    "Delta compression using up to 4 threads.\n",
    "Compressing objects: 100% (2/2), done.\n",
    "Writing objects: 100% (3/3), 308 bytes | 308.00 KiB/s, done.\n",
    "Total 3 (delta 0), reused 0 (delta 0)\n",
    "To github.com:michaelliao/learngit.git\n",
    "   f52c633..7a5e5dd  dev -> dev\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229311?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7bf3af0>"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51229311?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你的小伙伴已经向origin/dev分支推送了他的提交，而碰巧你也对同样的文件作了修改，并试图推送：\n",
    "```bash\n",
    "$ cat env.txt\n",
    "env\n",
    "\n",
    "$ git add env.txt\n",
    "\n",
    "$ git commit -m \"add new env\"\n",
    "[dev 7bd91f1] add new env\n",
    " 1 file changed, 1 insertion(+)\n",
    " create mode 100644 env.txt\n",
    "\n",
    "$ git push origin dev\n",
    "To github.com:michaelliao/learngit.git\n",
    " ! [rejected]        dev -> dev (non-fast-forward)\n",
    "error: failed to push some refs to 'git@github.com:michaelliao/learngit.git'\n",
    "hint: Updates were rejected because the tip of your current branch is behind\n",
    "hint: its remote counterpart. Integrate the remote changes (e.g.\n",
    "hint: 'git pull ...') before pushing again.\n",
    "hint: See the 'Note about fast-forwards' in 'git push --help' for details.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "推送失败，因为你的小伙伴的最新提交和你试图推送的提交有冲突，解决办法也很简单，Git已经提示我们，先用git pull把最新的提交从origin/dev抓下来，然后，在本地合并，解决冲突，再推送：\n",
    "```bash\n",
    "$ git pull\n",
    "There is no tracking information for the current branch.\n",
    "Please specify which branch you want to merge with.\n",
    "See git-pull(1) for details.\n",
    "\n",
    "    git pull <remote> <branch>\n",
    "\n",
    "If you wish to set tracking information for this branch you can do so with:\n",
    "\n",
    "    git branch --set-upstream-to=origin/<branch> dev\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "git pull也失败了，原因是没有指定本地dev分支与远程origin/dev分支的链接，根据提示，设置dev和origin/dev的链接：\n",
    "```bash\n",
    "$ git branch --set-upstream-to=origin/dev dev\n",
    "Branch 'dev' set up to track remote branch 'dev' from 'origin'.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再pull：\n",
    "```bash\n",
    "$ git pull\n",
    "Auto-merging env.txt\n",
    "CONFLICT (add/add): Merge conflict in env.txt\n",
    "Automatic merge failed; fix conflicts and then commit the result.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这回git pull成功，但是合并有冲突，需要手动解决，解决的方法和分支管理中的解决冲突完全一样。解决后，提交，再push：\n",
    "```bash\n",
    "$ git commit -m \"fix env conflict\"\n",
    "[dev 57c53ab] fix env conflict\n",
    "\n",
    "$ git push origin dev\n",
    "Counting objects: 6, done.\n",
    "Delta compression using up to 4 threads.\n",
    "Compressing objects: 100% (4/4), done.\n",
    "Writing objects: 100% (6/6), 621 bytes | 621.00 KiB/s, done.\n",
    "Total 6 (delta 0), reused 0 (delta 0)\n",
    "To github.com:michaelliao/learngit.git\n",
    "   7a5e5dd..57c53ab  dev -> dev\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229396?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a6501b20>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51229396?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因此，多人协作的工作模式通常是这样：\n",
    "\n",
    "首先，可以试图用`git push origin <branch-name>`推送自己的修改；\n",
    "\n",
    "如果推送失败，则因为远程分支比你的本地更新，需要先用`git pull`试图合并；\n",
    "\n",
    "如果合并有冲突，则解决冲突，并在本地提交；\n",
    "\n",
    "没有冲突或者解决掉冲突后，再用`git push origin <branch-name>`推送就能成功！\n",
    "\n",
    "如果`git pull`提示no tracking information，则说明本地分支和远程分支的链接关系没有创建，用命令`git branch --set-upstream-to <branch-name> origin/<branch-name>`。\n",
    "\n",
    "这就是多人协作的工作模式，一旦熟悉了，就非常简单。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "* 查看远程库信息，使用`git remote -v`；\n",
    "* 本地新建的分支如果不推送到远程，对其他人就是不可见的；\n",
    "* 从本地推送分支，使用`git push origin branch-name`，如果推送失败，先用`git pull`抓取远程的新提交；\n",
    "* 在本地创建和远程分支对应的分支，使用`git checkout -b branch-name origin/branch-name`，本地和远程分支的名称最好一致；\n",
    "* 建立本地分支和远程分支的关联，使用`git branch --set-upstream branch-name origin/branch-name`；\n",
    "* 从远程抓取分支，使用`git pull`，如果有冲突，要先处理冲突。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Rebase"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在上一节我们看到了，多人在同一个分支上协作时，很容易出现冲突。即使没有冲突，后push的童鞋不得不先pull，在本地合并，然后才能push成功。\n",
    "\n",
    "每次合并再push后，分支变成了这样：\n",
    "```bash\n",
    "$ git log --graph --oneline --abbrev-commit\n",
    "* d1be385 (HEAD -> master, origin/master) init hello\n",
    "*   e5e69f1 Merge branch 'dev'\n",
    "|\\  \n",
    "| *   57c53ab (origin/dev, dev) fix env conflict\n",
    "| |\\  \n",
    "| | * 7a5e5dd add env\n",
    "| * | 7bd91f1 add new env\n",
    "| |/  \n",
    "* |   12a631b merged bug fix 101\n",
    "|\\ \\  \n",
    "| * | 4c805e2 fix bug 101\n",
    "|/ /  \n",
    "* |   e1e9c68 merge with no-ff\n",
    "|\\ \\  \n",
    "| |/  \n",
    "| * f52c633 add merge\n",
    "|/  \n",
    "*   cf810e4 conflict fixed\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "总之看上去很乱，有强迫症的童鞋会问：为什么Git的提交历史不能是一条干净的直线？\n",
    "\n",
    "其实是可以做到的！\n",
    "\n",
    "Git有一种称为rebase的操作，有人把它翻译成“变基”。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNly1gsge3r8jzxj61lm0awjv902.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "先不要随m意展开想象。我们还是从实际问题出发，看看怎么把分叉的提交变成直线。\n",
    "\n",
    "在和远程分支同步后，我们对hello.py这个文件做了两次提交。用git log命令看看：\n",
    "```bash\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "* 582d922 (HEAD -> master) add author\n",
    "* 8875536 add comment\n",
    "* d1be385 (origin/master) init hello\n",
    "*   e5e69f1 Merge branch 'dev'\n",
    "|\\  \n",
    "| *   57c53ab (origin/dev, dev) fix env conflict\n",
    "| |\\  \n",
    "| | * 7a5e5dd add env\n",
    "| * | 7bd91f1 add new env\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意到Git用(HEAD -> master)和(origin/master)标识出当前分支的HEAD和远程origin的位置分别是582d922 add author和d1be385 init hello，本地分支比远程分支快两个提交。\n",
    "\n",
    "现在我们尝试推送本地分支：\n",
    "```bash\n",
    "$ git push origin master\n",
    "To github.com:michaelliao/learngit.git\n",
    " ! [rejected]        master -> master (fetch first)\n",
    "error: failed to push some refs to 'git@github.com:michaelliao/learngit.git'\n",
    "hint: Updates were rejected because the remote contains work that you do\n",
    "hint: not have locally. This is usually caused by another repository pushing\n",
    "hint: to the same ref. You may want to first integrate the remote changes\n",
    "hint: (e.g., 'git pull ...') before pushing again.\n",
    "hint: See the 'Note about fast-forwards' in 'git push --help' for details.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "很不幸，失败了，这说明有人先于我们推送了远程分支。按照经验，先pull一下：\n",
    "```bash\n",
    "$ git pull\n",
    "remote: Counting objects: 3, done.\n",
    "remote: Compressing objects: 100% (1/1), done.\n",
    "remote: Total 3 (delta 1), reused 3 (delta 1), pack-reused 0\n",
    "Unpacking objects: 100% (3/3), done.\n",
    "From github.com:michaelliao/learngit\n",
    "   d1be385..f005ed4  master     -> origin/master\n",
    " * [new tag]         v1.0       -> v1.0\n",
    "Auto-merging hello.py\n",
    "Merge made by the 'recursive' strategy.\n",
    " hello.py | 1 +\n",
    " 1 file changed, 1 insertion(+)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用git status看看状态：\n",
    "```bash\n",
    "$ git status\n",
    "On branch master\n",
    "Your branch is ahead of 'origin/master' by 3 commits.\n",
    "  (use \"git push\" to publish your local commits)\n",
    "\n",
    "nothing to commit, working tree clean\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "加上刚才合并的提交，现在我们本地分支比远程分支超前3个提交。\n",
    "```bash\n",
    "用git log看看：\n",
    "\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "*   e0ea545 (HEAD -> master) Merge branch 'master' of github.com:michaelliao/learngit\n",
    "|\\  \n",
    "| * f005ed4 (origin/master) set exit=1\n",
    "* | 582d922 add author\n",
    "* | 8875536 add comment\n",
    "|/  \n",
    "* d1be385 init hello\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对强迫症童鞋来说，现在事情有点不对头，提交历史分叉了。如果现在把本地分支push到远程，有没有问题？\n",
    "\n",
    "有！\n",
    "\n",
    "什么问题？\n",
    "\n",
    "不好看！\n",
    "\n",
    "有没有解决方法？\n",
    "\n",
    "有！\n",
    "\n",
    "这个时候，rebase就派上了用场。我们输入命令git rebase试试：\n",
    "```bash\n",
    "$ git rebase\n",
    "First, rewinding head to replay your work on top of it...\n",
    "Applying: add comment\n",
    "Using index info to reconstruct a base tree...\n",
    "M\thello.py\n",
    "Falling back to patching base and 3-way merge...\n",
    "Auto-merging hello.py\n",
    "Applying: add author\n",
    "Using index info to reconstruct a base tree...\n",
    "M\thello.py\n",
    "Falling back to patching base and 3-way merge...\n",
    "Auto-merging hello.py\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出了一大堆操作，到底是啥效果？再用git log看看：\n",
    "```bash\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "* 7e61ed4 (HEAD -> master) add author\n",
    "* 3611cfe add comment\n",
    "* f005ed4 (origin/master) set exit=1\n",
    "* d1be385 init hello\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "原本分叉的提交现在变成一条直线了！这种神奇的操作是怎么实现的？其实原理非常简单。我们注意观察，发现Git把我们本地的提交“挪动”了位置，放到了f005ed4 (origin/master) set exit=1之后，这样，整个提交历史就成了一条直线。rebase操作前后，最终的提交内容是一致的，但是，我们本地的commit修改内容已经变化了，它们的修改不再基于d1be385 init hello，而是基于f005ed4 (origin/master) set exit=1，但最后的提交7e61ed4内容是一致的。\n",
    "\n",
    "这就是rebase操作的特点：把分叉的提交历史“整理”成一条直线，看上去更直观。缺点是本地的分叉提交已经被修改过了。\n",
    "\n",
    "最后，通过push操作把本地分支推送到远程：\n",
    "```bash\n",
    "Mac:~/learngit michael$ git push origin master\n",
    "Counting objects: 6, done.\n",
    "Delta compression using up to 4 threads.\n",
    "Compressing objects: 100% (5/5), done.\n",
    "Writing objects: 100% (6/6), 576 bytes | 576.00 KiB/s, done.\n",
    "Total 6 (delta 2), reused 0 (delta 0)\n",
    "remote: Resolving deltas: 100% (2/2), completed with 1 local object.\n",
    "To github.com:michaelliao/learngit.git\n",
    "   f005ed4..7e61ed4  master -> master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用git log看看效果：\n",
    "```bash\n",
    "$ git log --graph --pretty=oneline --abbrev-commit\n",
    "* 7e61ed4 (HEAD -> master, origin/master) add author\n",
    "* 3611cfe add comment\n",
    "* f005ed4 set exit=1\n",
    "* d1be385 init hello\n",
    "...\n",
    "```\n",
    "远程分支的提交历史也是一条直线。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229455?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a8c022e0>"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51229455?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "* rebase操作可以把本地未push的分叉提交历史整理成直线；\n",
    "* rebase的目的是使得我们在查看历史提交的变化时更容易，因为分叉的提交需要三方对比。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 标签管理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "发布一个版本时，我们通常先在版本库中打一个标签（tag），这样，就唯一确定了打标签时刻的版本。将来无论什么时候，取某个标签的版本，就是把那个打标签的时刻的历史版本取出来。所以，标签也是版本库的一个快照。\n",
    "\n",
    "Git的标签虽然是版本库的快照，但其实它就是指向某个commit的指针（跟分支很像对不对？但是分支可以移动，标签不能移动），所以，创建和删除标签都是瞬间完成的。\n",
    "\n",
    "Git有commit，为什么还要引入tag？\n",
    "\n",
    "“请把上周一的那个版本打包发布，commit号是6a5819e...”\n",
    "\n",
    "“一串乱七八糟的数字不好找！”\n",
    "\n",
    "如果换一个办法：\n",
    "\n",
    "“请把上周一的那个版本打包发布，版本号是v1.2”\n",
    "\n",
    "“好的，按照tag v1.2查找commit就行！”\n",
    "\n",
    "所以，tag就是一个让人容易记住的有意义的名字，它跟某个commit绑在一起。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建标签"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在Git中打标签非常简单，首先，切换到需要打标签的分支上：\n",
    "```bash\n",
    "$ git branch\n",
    "* dev\n",
    "  master\n",
    "$ git switch master\n",
    "Switched to branch 'master'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，敲命令git tag <name>就可以打一个新标签：\n",
    "```bash\n",
    "$ git tag v1.0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以用命令git tag查看所有标签：\n",
    "```bash\n",
    "$ git tag\n",
    "v1.0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认标签是打在最新提交的commit上的。有时候，如果忘了打标签，比如，现在已经是周五了，但应该在周一打的标签没有打，怎么办？\n",
    "\n",
    "方法是找到历史提交的commit id，然后打上就可以了：\n",
    "```bash\n",
    "$ git log --pretty=oneline --abbrev-commit\n",
    "12a631b (HEAD -> master, tag: v1.0, origin/master) merged bug fix 101\n",
    "4c805e2 fix bug 101\n",
    "e1e9c68 merge with no-ff\n",
    "f52c633 add merge\n",
    "cf810e4 conflict fixed\n",
    "5dc6824 & simple\n",
    "14096d0 AND simple\n",
    "b17d20e branch test\n",
    "d46f35e remove test.txt\n",
    "b84166e add test.txt\n",
    "519219b git tracks changes\n",
    "e43a48b understand how stage works\n",
    "1094adb append GPL\n",
    "e475afc add distributed\n",
    "eaadf4e wrote a readme file\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "比方说要对add merge这次提交打标签，它对应的commit id是f52c633，敲入命令：\n",
    "```bash\n",
    "$ git tag v0.9 f52c633\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用命令git tag查看标签：\n",
    "```bash\n",
    "$ git tag\n",
    "v0.9\n",
    "v1.0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，标签不是按时间顺序列出，而是按字母排序的。可以用git show <tagname>查看标签信息：\n",
    "```bash\n",
    "$ git show v0.9\n",
    "commit f52c63349bc3c1593499807e5c8e972b82c8f286 (tag: v0.9)\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 21:56:54 2018 +0800\n",
    "\n",
    "    add merge\n",
    "\n",
    "diff --git a/readme.txt b/readme.txt\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，v0.9确实打在add merge这次提交上。\n",
    "\n",
    "还可以创建带有说明的标签，用-a指定标签名，-m指定说明文字：\n",
    "```bash\n",
    "$ git tag -a v0.1 -m \"version 0.1 released\" 1094adb\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用命令git show <tagname>可以看到说明文字：\n",
    "```bash\n",
    "$ git show v0.1\n",
    "tag v0.1\n",
    "Tagger: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 22:48:43 2018 +0800\n",
    "\n",
    "version 0.1 released\n",
    "\n",
    "commit 1094adb7b9b3807259d8cb349e7df1d4d6477073 (tag: v0.1)\n",
    "Author: Michael Liao <askxuefeng@gmail.com>\n",
    "Date:   Fri May 18 21:06:15 2018 +0800\n",
    "\n",
    "    append GPL\n",
    "\n",
    "diff --git a/readme.txt b/readme.txt\n",
    "...\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229543?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a7e18b20>"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame('https://www.bilibili.com/video/av51229543?zw', width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "* 命令`git tag <tagname>`用于新建一个标签，默认为`HEAD`，也可以指定一个`commit id`；\n",
    "* 命令`git tag -a <tagname> -m \"blablabla...\"`可以指定标签信息；\n",
    "* 命令`git tag`可以查看所有标签。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 操作标签"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果标签打错了，也可以删除：\n",
    "```bash\n",
    "$ git tag -d v0.1\n",
    "Deleted tag 'v0.1' (was f15b0dd)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为创建的标签都只存储在本地，不会自动推送到远程。所以，打错的标签可以在本地安全删除。\n",
    "\n",
    "如果要推送某个标签到远程，使用命令`git push origin <tagname>`：\n",
    "```bash\n",
    "$ git push origin v1.0\n",
    "Total 0 (delta 0), reused 0 (delta 0)\n",
    "To github.com:michaelliao/learngit.git\n",
    " * [new tag]         v1.0 -> v1.0\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "或者，一次性推送全部尚未推送到远程的本地标签：\n",
    "```bash\n",
    "$ git push origin --tags\n",
    "Total 0 (delta 0), reused 0 (delta 0)\n",
    "To github.com:michaelliao/learngit.git\n",
    " * [new tag]         v0.9 -> v0.9\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果标签已经推送到远程，要删除远程标签就麻烦一点，先从本地删除：\n",
    "```bash\n",
    "$ git tag -d v0.9\n",
    "Deleted tag 'v0.9' (was f52c633)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，从远程删除。删除命令也是push，但是格式如下：\n",
    "```bash\n",
    "$ git push origin :refs/tags/v0.9\n",
    "To github.com:michaelliao/learngit.git\n",
    " - [deleted]         v0.9\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要看看是否真的从远程库删除了标签，可以登陆GitHub查看。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"800\"\n",
       "            height=\"450\"\n",
       "            src=\"https://www.bilibili.com/video/av51229695?zw\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f91a8c22460>"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "IFrame(\"https://www.bilibili.com/video/av51229695?zw\", width=800, height=450)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "* 命令`git push origin <tagname>`可以推送一个本地标签；\n",
    "* 命令`git push origin --tags`可以推送全部未推送过的本地标签；\n",
    "* 命令`git tag -d <tagname>`可以删除一个本地标签；\n",
    "* 命令`git push origin :refs/tags/<tagname>`可以删除一个远程标签。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用GitHub"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们一直用GitHub作为免费的远程仓库，如果是个人的开源项目，放到GitHub上是完全没有问题的。其实GitHub还是一个开源协作社区，通过GitHub，既可以让别人参与你的开源项目，也可以参与别人的开源项目。\n",
    "\n",
    "在GitHub出现以前，开源项目开源容易，但让广大人民群众参与进来比较困难，因为要参与，就要提交代码，而给每个想提交代码的群众都开一个账号那是不现实的，因此，群众也仅限于报个bug，即使能改掉bug，也只能把diff文件用邮件发过去，很不方便。\n",
    "\n",
    "但是在GitHub上，利用Git极其强大的克隆和分支功能，广大人民群众真正可以第一次自由参与各种开源项目了。\n",
    "\n",
    "如何参与一个开源项目呢？比如人气极高的bootstrap项目，这是一个非常强大的CSS框架，你可以访问它的项目主页https://github.com/twbs/bootstrap，点“Fork”就在自己的账号下克隆了一个bootstrap仓库，然后，从自己的账号下clone：\n",
    "```bash\n",
    "git clone git@github.com:michaelliao/bootstrap.git\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一定要从自己的账号下clone仓库，这样你才能推送修改。如果从bootstrap的作者的仓库地址git@github.com:twbs/bootstrap.git克隆，因为没有权限，你将不能推送修改。\n",
    "\n",
    "Bootstrap的官方仓库twbs/bootstrap、你在GitHub上克隆的仓库my/bootstrap，以及你自己克隆到本地电脑的仓库，他们的关系就像下图显示的那样："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNgy1gsgifs8iy9j31ju08y74t.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你想修复bootstrap的一个bug，或者新增一个功能，立刻就可以开始干活，干完后，往自己的仓库推送。\n",
    "\n",
    "如果你希望bootstrap的官方库能接受你的修改，你就可以在GitHub上发起一个pull request。当然，对方是否接受你的pull request就不一定了。\n",
    "\n",
    "如果你没能力修改bootstrap，但又想要试一把pull request，那就Fork一下我的仓库：[learngit](https://github.com/michaelliao/learngit)， 创建一个your-github-id.txt的文本文件，写点自己学习Git的心得，然后推送一个`pull request`给我，我会视心情而定是否接受。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小结\n",
    "\n",
    "* 在GitHub上，可以任意Fork开源仓库；\n",
    "* 自己拥有Fork后的仓库的读写权限；\n",
    "* 可以推送pull request给官方仓库来贡献代码。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用Gitee"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用GitHub时，国内的用户经常遇到的问题是访问速度太慢，有时候还会出现无法连接的情况（原因你懂的）。\n",
    "\n",
    "如果我们希望体验Git飞一般的速度，可以使用国内的Git托管服务——Gitee（gitee.com）。\n",
    "\n",
    "和GitHub相比，Gitee也提供免费的Git仓库。此外，还集成了代码质量检测、项目演示等功能。对于团队协作开发，Gitee还提供了项目管理、代码托管、文档管理的服务，5人以下小团队免费。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用Gitee和使用GitHub类似，我们在Gitee上注册账号并登录后，需要先上传自己的SSH公钥。选择右上角用户头像 -> 菜单“修改资料”，然后选择“SSH公钥”，填写一个便于识别的标题，然后把用户主目录下的`.ssh/id_rsa.pub`文件的内容粘贴进去"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNgy1gsgijpkcvkj31la0rs7pk.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "点击“确定”即可完成并看到刚才添加的Key："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNgy1gsgiqw7c3uj31lo0cwdm3.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果我们已经有了一个本地的git仓库（例如，一个名为learngit的本地库），如何把它关联到Gitee的远程库上呢？\n",
    "\n",
    "首先，我们在Gitee上创建一个新的项目，选择右上角用户头像 -> 菜单“控制面板”，然后点击“创建项目”："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNgy1gsgisao28kj31ev0u07fr.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "项目名称最好与本地库保持一致：\n",
    "\n",
    "然后，我们在本地库上使用命令git remote add把它和Gitee的远程库关联：\n",
    "```bash\n",
    "$ git remote add origin git@gitee.com:liaoxuefeng/learngit.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之后，就可以正常地用`git push`和`git pull`推送了！\n",
    "\n",
    "如果在使用命令git remote add时报错：\n",
    "```bash\n",
    "$ git remote add origin git@gitee.com:liaoxuefeng/learngit.git\n",
    "fatal: remote origin already exists.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这说明本地库已经关联了一个名叫origin的远程库，此时，可以先用`git remote -v`查看远程库信息：\n",
    "```bash\n",
    "$ git remote -v\n",
    "origin\tgit@github.com:michaelliao/learngit.git (fetch)\n",
    "origin\tgit@github.com:michaelliao/learngit.git (push)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以看到，本地库已经关联了origin的远程库，并且，该远程库指向GitHub。\n",
    "\n",
    "我们可以删除已有的GitHub远程库：\n",
    "```bash\n",
    "$ git remote rm origin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再关联Gitee的远程库（注意路径中需要填写正确的用户名）：\n",
    "```bash\n",
    "$ git remote add origin git@gitee.com:liaoxuefeng/learngit.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "此时，我们再查看远程库信息：\n",
    "```bash\n",
    "$ git remote -v\n",
    "origin\tgit@gitee.com:liaoxuefeng/learngit.git (fetch)\n",
    "origin\tgit@gitee.com:liaoxuefeng/learngit.git (push)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在可以看到，origin已经被关联到Gitee的远程库了。通过git push命令就可以把本地库推送到Gitee上。\n",
    "\n",
    "有的小伙伴又要问了，一个本地库能不能既关联GitHub，又关联Gitee呢？\n",
    "\n",
    "答案是肯定的，因为git本身是分布式版本控制系统，可以同步到另外一个远程库，当然也可以同步到另外两个远程库。\n",
    "\n",
    "使用多个远程库时，我们要注意，git给远程库起的默认名称是origin，如果有多个远程库，我们需要用不同的名称来标识不同的远程库。\n",
    "\n",
    "仍然以learngit本地库为例，我们先删除已关联的名为origin的远程库：\n",
    "```bash\n",
    "$ git remote rm origin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后，先关联GitHub的远程库：\n",
    "```bash\n",
    "$ git remote add github git@github.com:michaelliao/learngit.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，远程库的名称叫github，不叫origin了。\n",
    "\n",
    "接着，再关联Gitee的远程库：\n",
    "```bash\n",
    "$ git remote add gitee git@gitee.com:liaoxuefeng/learngit.git\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同样注意，远程库的名称叫gitee，不叫origin。\n",
    "\n",
    "现在，我们用`git remote -v`查看远程库信息，可以看到两个远程库：\n",
    "```bash\n",
    "git remote -v\n",
    "gitee\tgit@gitee.com:liaoxuefeng/learngit.git (fetch)\n",
    "gitee\tgit@gitee.com:liaoxuefeng/learngit.git (push)\n",
    "github\tgit@github.com:michaelliao/learngit.git (fetch)\n",
    "github\tgit@github.com:michaelliao/learngit.git (push)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果要推送到GitHub，使用命令：\n",
    "```bash\n",
    "git push github master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果要推送到Gitee，使用命令：\n",
    "```bash\n",
    "git push gitee master\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这样一来，我们的本地库就可以同时与多个远程库互相同步："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://tva1.sinaimg.cn/large/008i3skNgy1gsgj5stijmj31kc07gaad.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Gitee也同样提供了Pull request功能，可以让其他小伙伴参与到开源项目中来。你可以通过Fork我的仓库：https://gitee.com/liaoxuefeng/learngit，创建一个your-gitee-id.txt的文本文件， 写点自己学习Git的心得，然后推送一个pull request给我，这个仓库会在Gitee和GitHub做双向同步。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc-autonumbering": true,
  "toc-showcode": false,
  "toc-showmarkdowntxt": false
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
